package com.tianye.salon.controller.admin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tianye.salon.controller.BaseController;
import com.tianye.salon.dto.AdminUserFormDto;
import com.tianye.salon.exception.MyException;
import com.tianye.salon.model.AdminRole;
import com.tianye.salon.model.AdminUser;
import com.tianye.salon.service.AdminRoleService;
import com.tianye.salon.service.AdminUserService;
import com.tianye.salon.util.CheckUtil;
import com.tianye.salon.util.ConversionMd5;




@Controller
@RequestMapping("/admin-user")
public class AdminUserController extends BaseController {
	protected Logger logger = LoggerFactory.getLogger(AdminUserController.class);
	@Autowired
	private AdminUserService adminUserService;
	@Autowired
	private AdminRoleService adminRoleService;
	
	/**
	 * 初始化先跳转到页面，再通过ajax调用获取列表数据
	 * @param request
	 * @return
	 */
	@RequestMapping("index")
	public ModelAndView index(HttpServletRequest request){
		ModelAndView mav = new ModelAndView("/admin/adminuser");
		
		return mav;
	}
	/**
	 * 后台请求列表信息
	 * @param username 用户名
	 * @param type 会员类型
	 * @param areaId 地区id
	 * @param level 会员级别
	 * @param page 查询页码
	 * @param size 每页条数
	 * @param pid 省份id
	 * @param cid 城市id
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/ajaxadminuserlist")
	@ResponseBody
	public Object findAdminUserList(Integer page,Integer size){
		Map<String,Object> retMap = null;
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("page", page != null ? page : 1);
		map.put("size", size != null ? size: 20);
		try {
			retMap = adminUserService.getUserList(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return retMap;	
	}
	
	@RequestMapping(value="add")
	public String add(Model model) throws Exception{
		model.addAttribute("userform", new AdminUserFormDto());
		model.addAttribute("roles", getRoles());
		
		return "/admin/adminuser_add";
	}
	
	@RequestMapping(value="update/{id}")
	public String update(@PathVariable int id, Model model) throws Exception{
		AdminUserFormDto userform = adminUserService.selectFormByPrimaryKey(id);
		model.addAttribute("userform", userform);
		model.addAttribute("roles", getRoles());
		
		return "/admin/adminuser_update";
	}
	
	@RequestMapping(value="reparepass")
	public String reparepass(int id, Model model){
		AdminUserFormDto userform = adminUserService.selectFormByPrimaryKey(id);
		model.addAttribute("userform", userform);
		
		return "/admin/adminuser_reparepass";
	}
	
	@RequestMapping(value="formadd", produces="application/json; charset=utf-8")
	public String formadd(@ModelAttribute("userform") @Valid AdminUserFormDto userform, BindingResult bindingResult, Model model, HttpSession session) throws Exception {
		
		if (bindingResult.hasErrors()) {
			model.addAttribute("roles", getRoles());
			
            return "/admin/adminuser_add";
        }
		
		String pass = userform.getPwd();
		String confirmPass = userform.getConfirmPwd();
		
		try {
			if(!pass.equals(confirmPass)){
				throw new MyException("确认密码错误！");
			}
			
			AdminUser user = userform.toUser();
			user.setPwd(ConversionMd5.toMd5(user.getPwd()));
			
			adminUserService.insert(user);
		} catch (MyException e) {
			e.printStackTrace();
			bindingResult.rejectValue("confirmPwd", "userform.confirmPwd", e.getMessage());
			
			model.addAttribute("roles", getRoles());
			
            return "/admin/adminuser_add";
		}
		
		return "redirect:/admin-user/index";
	}
	
	@RequestMapping(value="formupdate")
	public String formupdate(@ModelAttribute("userform") @Valid AdminUserFormDto userform, BindingResult bindingResult, Model model, HttpSession session) throws Exception{
		if (bindingResult.hasErrors()) {
			model.addAttribute("roles", getRoles());
			
            return "/admin/adminuser_update";
        }
		
		//System.out.println("userform is:"+userform.toString());
		try {
			AdminUser user = userform.toUser();
			
			//System.out.println("user is:"+user.toString());
			
			adminUserService.updateByPrimaryKeySelective(user);
		} catch (MyException e) {
			e.printStackTrace();
			bindingResult.rejectValue("confirmPwd", "userform.confirmPwd", e.getMessage());
			
			model.addAttribute("roles", getRoles());
			
            return "/admin/adminuser_add";
		}
		
		return "redirect:/admin-user/index";
	}
	
	@RequestMapping(value="formreparepass")
	public String formreparepass(@ModelAttribute("userform") @Valid AdminUserFormDto userform, BindingResult bindingResult, Model model) throws Exception{
		if(bindingResult.hasErrors()){
			List<ObjectError> errors = bindingResult.getAllErrors();
			
			for(ObjectError err:errors){
				logger.error(err.getCode()+" - "+err.getDefaultMessage());
			}
			
			return "/admin/adminuser_reparepass";
		}
		
		String pass = userform.getPwd();
		String confirmPass = userform.getConfirmPwd();
		
		try {
			if(!pass.equals(confirmPass)){
				throw new MyException("确认密码错误！");
			}
			
			AdminUser user = userform.toUser();
			user.setPwd(ConversionMd5.toMd5(user.getPwd()));
			
			adminUserService.updateByPrimaryKeySelective(user);
		} catch (MyException e) {
			e.printStackTrace();
			bindingResult.rejectValue("confirmPwd", "userform.confirmPwd", e.getMessage());
			
            return "/admin/adminuser_reparepass";
		}
		
		return "redirect:/admin-user/index";
	}
	
	@RequestMapping(value="ajaxdelete")
	@ResponseBody
	public Map<String,Object> delete(String[] userIds) throws Exception{
		List<String> list = Arrays.asList(userIds);
		List<Integer> ids = new ArrayList<Integer>();
		
		if(CheckUtil.isEmpty(list)){
			return getFailRtn("参数不能为空");
		}
		
		for(String idStr : list){
			Integer id = 0;
			if(idStr != null && !"".equals(idStr)){
				id = Integer.parseInt(idStr);
				AdminUser user = adminUserService.selectById(id);
				if(null != user){
					ids.add(id);
				}
			}
		}
		if (ids != null && ids.size() > 0) {
			return adminUserService.batchDelUsers(ids);
		}else{
			return getFailRtn("数据库中不存在所选择回收机");
		}
		
	}

	public List<AdminRole> getRoles() throws Exception{
		List<AdminRole> roles = adminRoleService.selectAll();
		roles.add(0, new AdminRole(0, "", "", null));
		
		return roles;
	}
	
	
}
